package com.google.gwt.sample.hello.client.notgenerated.eventFramework.controler;

import java.util.Date;

import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.sample.hello.client.notgenerated.eventFramework.Accessor;
import com.google.gwt.sample.hello.client.notgenerated.eventFramework.Property;
import com.google.gwt.sample.hello.client.notgenerated.eventFramework.PropertyChangeEvent;
import com.google.gwt.sample.hello.client.notgenerated.eventFramework.PropertyChangeListener;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

@SuppressWarnings("deprecation")
public class DateToTextField implements PropertyChangeListener<Date>,
		ChangeListener, KeyboardListener {

	private TextBox field;
	Accessor<Date> accessor;

	public DateToTextField(TextBox f, Property<Date> p) {
		this.accessor = p.getAccessor();
		this.field = f;
		if (accessor.get()!= null)
			field.setText(DateTimeFormat.getShortDateFormat().format(accessor.get()));
		f.addKeyboardListener(this);
		f.addChangeListener(this);
		p.addPropertyChangeListener(this);


	}

	public void onChange(Widget sender) {
	    String sValue = ((TextBox) sender).getText();
	    if (!sValue.equals("")) {
	      try {
	        Date date = new Date(sValue);
	        String formattedValue = DateTimeFormat.getShortDateFormat().format(date);
	        
	        accessor.set(date);
		
	        field.setText(formattedValue);
	      	}catch(IllegalArgumentException e){
	      		field.setText("invalid");
		      }
	      }
	}

	public void propertyChanged(PropertyChangeEvent<Date> evt) {
		if (!field.getText().equals(evt.getNewValue())) {
			field.setText(DateTimeFormat.getShortDateFormat().format(evt.getNewValue()));
		}
	}

	public void onKeyDown(Widget sender, char keyCode, int modifiers) {

	}

	public void onKeyPress(Widget sender, char keyCode, int modifiers) {

	}

	public void onKeyUp(Widget sender, char keyCode, int modifiers) {
	}

}
